﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using System.Data;

namespace ProjectScheduling
{
    public partial class CountWorkHourPage : UserControl
    {
        public readonly static CountWorkHourPage b = new();
        private List<ProjectTypes> types = ProjectTypeDao.Base.FindAll(it => true);
        private Action<DataGridViewCellEventArgs>? showDetail;
        public CountWorkHourPage()
        {
            InitializeComponent();
            txt_search_start.Value = DateTime.Parse(DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd"));
            Dock = DockStyle.Fill;
            view_all.AutoGenerateColumns = false;
            Btn_search_Click(this, new EventArgs());
            txt_search_type.Items.Clear();
            txt_search_type.Items.Add("全部");
            txt_search_type.Items.AddRange(types.Select(it => it.Name ?? "").ToArray());
            txt_search_type.SelectedIndex = 0;
            view_all.CellContentClick += (s, e1) =>
            {
                showDetail?.Invoke(e1);
            };
        }

        private void Btn_search_Click(object sender, EventArgs e)
        {
            var start = txt_search_start.Value;
            var end = txt_search_end.Value.AddDays(1);
            DataTable dt1;
            int type = 0;
            if (txt_search_type.SelectedIndex > 0)
            {
                type = types[txt_search_type.SelectedIndex - 1].Id;
            }
            var table = PreparedStaffDao.Base.GroupToTable(start, end, type, out dt1);
            view_all.DataSource = table;
            lb_staffCount.Text = table.Rows.Count.ToString();
            showDetail = (e1) =>
            {
                if (e1.RowIndex < 0) return;
                if (e1.ColumnIndex != 4) return;
                string fName(string name) => view_all.Rows[e1.RowIndex].Cells[name].Value?.ToString() ?? "";
                var g = dt1.Clone();
                foreach (DataRow r in dt1.Rows)
                {
                    if (r["StaffId"].ToString() == fName("StaffId"))
                    {
                        var r1 = g.NewRow();
                        foreach (DataColumn col in dt1.Columns)
                        {
                            r1[col.ColumnName] = r[col.ColumnName].ToString();
                        }
                        g.Rows.Add(r1);
                    }
                }
                WorkHourStaffDataListForm.b.Text = $"{fName("员工姓名")} 期间项目统计";
                WorkHourStaffDataListForm.b.Init(g);
            };
        }

    }
}
